import {
	config,
	TOKEN_PRE
} from '../request/config.js'

import {joinParamsUrl} from '@/utils/joinParamsUrl.js'

class HTTP {
	static isTokenExpire=false //token是否已经过期
	constructor() {
		this.baseUrl = config.base_url
	}

	request({
		url,
		data = {},
		method = 'get',
		isToken=false,
		isLoading=false,
		params=[]
	}) {
		return new Promise((resolve, reject) => {
			url = params.length ? joinParamsUrl(url,params) : url
			
			if(isToken && HTTP.isTokenExpire){
				reject()
			}
			
			this._request(url, resolve, reject, data, method,isToken,isLoading)
		})
	}

	_request(url, resolve, reject, data = {}, method = 'get',isToken,isLoading) {
		const requestConfig = {
			url: `${this.baseUrl}${url}`,
			method: method,
			data: data,
			header: {
				'authorization': TOKEN_PRE+uni.getStorageSync('token')
			},
			success: (res) => {
				if (res.data.code===200) {
					resolve(res.data)
					HTTP.isTokenExpire=false
				} else {
					const {
						data,
						statusCode
					} = res
					
					switch(statusCode){
						case 401:
							uni.$emit('tips',data.data,'error')
							uni.$emit('userStore',{})
							uni.getStorageSync('token') && uni.$emit('wxLogin')
							uni.removeStorageSync('token')
							HTTP.isTokenExpire=true
							break
						case 404:
							uni.$emit('tips','未知请求','error')
							break
						case 470:
							uni.removeStorageSync('homeData')
							uni.setStorageSync('isDeleteDormitory',true)
							uni.reLaunch({
								url:'/pages/Dormitorys/Dormitorys'
							})
							break
						case 471:
							uni.$emit('tips',data.data.msg,'error',3000)
							setTimeout(()=>{
								uni.reLaunch({
									url:'/pages/Dormitory/Dormitory'
								})
							},3000)
							break
						default:
							uni.$emit('tips',data.data?.msg || data.data,'error')
							break
					}
					resolve(res.data)
				}
				uni.hideLoading()
			},
		}
		isLoading && uni.showLoading({
			title:'加载中'
		})
		uni.request(requestConfig)
	}

}

export {
    HTTP
}